package com.ias.agdis_r.manager;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;

import com.ias.agdis_r.R;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.sdcard.SDcard;
import com.ias.agdis_r.util.ShowToast;

/**
 * 操作本地数据库类（数据存在SCcard中）
 * 
 * @author liuhuanlei
 * 
 */
public class XmlManager {

	private String SDPATH;
	public static final String packageName = "IASDataBase";// SD卡存放数据文件的目录，可手动配置
	private SDRemindThread sdRemindThread = null;
	private static XmlManager instance = null;// 单例

	private XmlManager() {
	}

	/**
	 * 插入数据
	 * 
	 * @param tableName
	 * @param colName
	 * @param value
	 */
	public boolean inert(String tableName, String colName, String value) {
		SDPATH = SDcard.getSDPATH();
		if (SDPATH.equals("")) {
			StartSDRemind();
			return false;
		}
		HashMap<String, String> map = ReadXML(packageName, tableName + ".xml");// 原数据库数据

		map.put(colName, value);// 更新或是新加

		String xmlString = getStringXml(map);// 将要输出的数据转换成xml格式

		writeXML(tableName + ".xml", xmlString);
		return true;
	}

	/**
	 * 插入数据
	 * 
	 * @param tableName
	 * @param colName
	 * @param value
	 */
	public boolean inert(String packName, String tableName, String colName, String value) {
		SDPATH = SDcard.getSDPATH();
		if (SDPATH.equals("")) {
			StartSDRemind();
			return false;
		}
		HashMap<String, String> map = ReadXML(packName, tableName + ".xml");// 原数据库数据

		map.put(colName, value);// 更新或是新加

		String xmlString = getStringXml(map);// 将要输出的数据转换成xml格式

		writeXML(packName, tableName + ".xml", xmlString);
		return true;
	}

	/**
	 * 查询数据
	 * 
	 * @param tableName
	 *            表名
	 * @param colName
	 *            列名
	 * @return
	 */
	public String select(String tableName, String colName) {

		return select(packageName, tableName, colName);
	}

	/**
	 * 查询数据
	 * 
	 * @param 配置文件包
	 * 
	 * @param tableName
	 *            表名
	 * @param colName
	 *            列名
	 * @return
	 */
	public String select(String packageName, String tableName, String colName) {

		SDPATH = SDcard.getSDPATH(); // 检测SD卡是否存在
		String filePath = SDPATH + "/" + packageName + "/" + tableName + ".xml";// 文件目录
		String value = null;
		try {
			if (SDPATH.equals("")) {
				StartSDRemind();
			} else if (SDcard.isFileExist(filePath)) {// 如果文件不存在，则返回""

				HashMap<String, String> map = ReadXML(packageName, tableName + ".xml");

				value = map.get(colName);
			}
		} catch (Exception e) {

		}

		return value == null ? "" : value;
	}

	/**
	 * 未检测到SD卡的提示信息
	 */
	private void StartSDRemind() {
		if (sdRemindThread == null) {
			sdRemindThread = new SDRemindThread();
			sdRemindThread.start();
		}
	}

	/**
	 * 未检测到SD卡的提示信息线程
	 */
	class SDRemindThread extends Thread {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			while (true) {
				ParameterModel.SDCardDisabled = true;
				if (!ParameterModel.shutdownFlag) {
					ShowToast.get().showLongTime(DataBaseManager.getInstance().getContext().getString(R.string.noSDcard));
					EffectManager.getInstance().vibrate();
					EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_SDCARD_UNABLE);
				}

				try {
					Thread.sleep(5 * 1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

	}

	/**
	 * 读取XML文件
	 * 
	 * @param packageName
	 *            包名
	 * @param fileName
	 *            文件名
	 * @return HashMap<String, String> key:字段名 value:值
	 */
	public HashMap<String, String> ReadXML(String packageName, String fileName) {
		HashMap<String, String> map = new HashMap<String, String>();
		DocumentBuilderFactory docBuilderFactory = null;
		DocumentBuilder docBuilder = null;
		Document doc = null;
		InputSource is = null;
		String filePath = SDPATH + "/" + packageName + "/" + fileName;// 在sd卡上存放的xml路径
		FileInputStream fileIS = null;
		InputStreamReader isr = null;
		try {
			docBuilderFactory = DocumentBuilderFactory.newInstance();
			docBuilder = docBuilderFactory.newDocumentBuilder();
			// 创建一个文件
			File f = new File(filePath);
			isr = new InputStreamReader(new FileInputStream(f.getAbsolutePath()), "UTF-8"); // 以GBK的方式读取XML，解决读取中文乱码
			is = new InputSource();
			is.setCharacterStream(isr);
			doc = docBuilder.parse(is);
			// root element
			Element root = (Element) doc.getDocumentElement();
			// NodeList nodes = root.getElementsByTagName("map");
			// NodeList nodeList = nodes.item(0).getChildNodes();
			NodeList nodeList = root.getChildNodes();
			for (int j = 0; j < nodeList.getLength(); j++) {
				if (nodeList.item(j).getNodeType() == Node.ELEMENT_NODE) {
					Element stringElement = (Element) nodeList.item(j);
					String key = stringElement.getAttribute("name");
					if (S.isNotEmpty(key)) {
						String value = "";
						Node node = stringElement.getFirstChild();
						if (node != null) {
							value = S.valueOf(stringElement.getFirstChild().getNodeValue());
						}
						map.put(key, value);
					}
				}
			}
		} catch (IOException e) {
		} catch (SAXException e) {
		} catch (ParserConfigurationException e) {
		} finally {
			doc = null;
			docBuilder = null;
			docBuilderFactory = null;
			is = null;
			if (fileIS != null)
				try {
					fileIS.close();
				} catch (IOException e) {
					e.printStackTrace();
				} // 关闭输入流

			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return map;
	}

	/**
	 * 将数据写入到SD卡中
	 * 
	 * @param fileName
	 *            文件名
	 * @param outStr
	 *            输出的数据
	 * @return
	 */
	public File writeXML(String fileName, String outStr) {

		return writeXML(packageName, fileName, outStr);
	}

	/**
	 * 将数据写入到SD卡中
	 * 
	 * @param fileName
	 *            文件名
	 * @param outStr
	 *            输出的数据
	 * @return
	 */
	public File writeXML(String packageName, String fileName, String outStr) {
		File file = null;
		BufferedWriter writer = null;
		String path = SDPATH + "/" + packageName;// 包目录
		String filePath = SDPATH + "/" + packageName + "/" + fileName;// 文件目录
		try {
			if (!SDcard.isFileExist(path)) {// 如果目录不存在，则创建目录
				SDcard.creatSDDir(path);
			}
			file = SDcard.creatSDFile(filePath);// 创建文件

			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), "gbk");
			writer = new BufferedWriter(write);
			writer.write(outStr);
			write.flush();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	/**
	 * 将数据封装成xml格式
	 */
	public String getStringXml(HashMap<String, String> map) {
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			serializer.setOutput(writer);

			// <?xml version=”1.0″ encoding="utf-8″ standalone=”yes”?>
			serializer.startDocument("utf-8", true);
			// <map>
			serializer.startTag("", "map");

			// <String name="key"> value </String>
			Iterator it = map.entrySet().iterator();
			while (it.hasNext()) {// 循环打印map下的String节点
				Entry entry = (Entry) it.next();
				serializer.startTag("", "string");
				serializer.attribute("", "name", entry.getKey().toString());
				serializer.text(entry.getValue().toString());
				serializer.endTag("", "string");

			}
			// </map>
			serializer.endDocument();
			return writer.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/*
	 * 获取单例对象
	 */
	public static XmlManager getInstance() {
		if (instance == null) {
			instance = new XmlManager();
		}
		return instance;
	}

}
